/**
 * tabBar页面路径列表 (用于链接跳转时判断)
 * tabBarLinks为常量, 无需修改
 */
const tabBarLinks = [
  'pages/index/index',
  'pages/category/index',
  'pages/flow/index',
  'pages/user/index'
];

App({

  /**
   * 全局变量
   */
  globalData: {
    platform: 'ios',
    pixelRatio: 2,
    user_id: null,
    studentOpt: {},
    height: 0,
    statusBarHeight: 20,
    navHeight: 64,
    navTitleTop: 26,
    winHeight: 655,
    winWidth: 750,
    screenWidth: 375,
    screenHeight: 812
  },
  api_root: '', // api地址
  siteInfo: require('siteinfo.js'),
  /**
   * 生命周期函数--监听小程序初始化
   */
  onLaunch() {
    // 设置api地址
    this.setApiRoot();
    // 获取屏幕参数
    try {
      const res = wx.getSystemInfoSync()
      if (res.platform == 'ios') {
        this.globalData.platform = 'ios'
      } else if (res.platform == 'android') {
        this.globalData.platform = 'android'
      }
      // 导航高度
      let navHeight = res.statusBarHeight
      // 屏幕宽度/高度，单位px
      this.globalData.screenWidth = res.screenWidth
      this.globalData.screenHeight = res.screenHeight
      // 状态栏的高度，单位px
      this.globalData.statusBarHeight = res.statusBarHeight
      // 设备像素比
      this.globalData.pixelRatio = res.pixelRatio
      // 可使用窗口宽度，单位px
      this.globalData.winWidth = res.windowWidth
      // 安卓时，胶囊距离状态栏8px，iOS距离4px
      if (res.system.indexOf('Android') !== -1) {
        this.globalData.navHeight = navHeight + 14 + 32
        this.globalData.navTitleTop = navHeight + 8
        // 视窗高度 顶部有占位栏时
        this.globalData.winHeight = res.screenHeight - navHeight - 14 - 32
        // tab主页视窗高度
        this.globalData.winHeightTab = res.windowHeight - navHeight - 14 - 32
      } else {
        this.globalData.navHeight = navHeight + 12 + 32
        this.globalData.navTitleTop = navHeight + 4
        // 视窗高度 顶部有占位栏时
        this.globalData.winHeight = res.screenHeight - navHeight - 12 - 32
        // tab主页视窗高度
        this.globalData.winHeightTab = res.windowHeight - navHeight - 12 - 32
      }
    } catch (e) {
      console.log(e)
    }
  },
  /**
   * 当小程序启动，或从后台进入前台显示，会触发 onShow
   */
  onShow(options) {

  },
  /**
   * 设置api地址
   */
  setApiRoot() {
    this.api_root = this.siteInfo.siteroot + '';
    this.base_url = this.siteInfo.baseUrl;
  },
  /**
   * 获取小程序基础信息
   */
  getWxappBase(callback) {
    let App = this;
    App._get('wxapp/base', {}, function (result) {
      // 记录小程序基础信息
      wx.setStorageSync('wxapp', result.data.wxapp);
      callback && callback(result.data.wxapp);
    }, false, false);
  },
  /**
   * 执行用户登录
   */
  doLogin() {
    // 保存当前页面
    let pages = getCurrentPages();
    if (pages.length) {
      let currentPage = pages[pages.length - 1];
      "pages/login/login" != currentPage.route &&
      wx.setStorageSync("currentPage", currentPage);
    }
    // 跳转授权页面
    wx.navigateTo({
      url: "/pages/login/login"
    });
  },
  /**
   * 当前用户id
   */
  getUserId() {
    return wx.getStorageSync('user_id');
  },
  /**
   * 显示成功提示框
   */
  showSuccess(msg, callback) {
    wx.showToast({
      title: msg,
      icon: 'success',
      success() {
        callback && (setTimeout(function () {
          callback();
        }, 1500));
      }
    });
  },
  /**
   * tips
   * */
  showMsg(msg, callback) {
    wx.showToast({
      title: msg,
      icon: 'none',
      success() {
        callback && (setTimeout(function () {
          callback();
        }, 1500));
      }
    });
  },
  /**
   * 显示失败提示框
   */
  showError(msg, callback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success(res) {
        // callback && (setTimeout(function() {
        //   callback();
        // }, 1500));
        callback && callback();
      }
    });
  },
  alert: function (params) {
    var title = params.hasOwnProperty('title') ? params['title'] : '友情提示';
    var content = params.hasOwnProperty('content') ? params['content'] : '';
    var showCancel = params.hasOwnProperty('showCancel') ? params['showCancel'] : false;
    wx.showModal({
      title: title,
      content: content,
      showCancel: showCancel,
      confirmColor:'#F7B40A',
      cancelColor:'#333333',
      cancelText: "取消",
      confirmText: "确定",
      success: function (res) {
        if (res.confirm) { //用户点击确定
          if (params.hasOwnProperty('cb_confirm') && typeof(params.cb_confirm) == "function") {
            params.cb_confirm();
          }
        } else {
          if (params.hasOwnProperty('cb_cancel') && typeof(params.cb_cancel) == "function") {
            params.cb_cancel();
          }
        }
      }
    })
  },
  /**
   * get请求
   */
  _get(url, data, success, fail, complete, check_login) {
    wx.showNavigationBarLoading();
    let App = this;
    // 构造请求参数
    data = data || {};
    // 构造get请求
    let request = function () {
      data.encoding = 'utf-8';
      if (!data.userid) { data.userid = wx.getStorageSync('user_id');}
      let accessToken= wx.getStorageSync('sign');
      wx.request({
        url: App.api_root + url,
        header: {
          // 'content-type': 'application/json'
          'content-type': 'application/x-www-form-urlencoded',
          accessToken:  accessToken
        },
        data: data,
        success(res) {
          if (res.statusCode !== 200 || typeof res.data !== 'object') {
            App.showError('网络请求出错');
            return false;
          }
          if (res.data.returnvalue == 1000) {
            // 授权
            wx.hideNavigationBarLoading();
          } else if (res.data.returnvalue == 'falseNologin') {
            // 登录态失效, 重新登录
            wx.hideNavigationBarLoading();
            App.showError('登录过期,请重新登录', function () {
              App.doLogin();
            });
          } else if (res.data.returnvalue == -1) {
            App.showError(res.data.msg);
            return false;
          } else {
            success && success(res.data);
          }
        },
        fail(res) {
          App.showError(res.errMsg, function () {
            fail && fail(res);
          });
        },
        complete(res) {
          wx.hideNavigationBarLoading();
          complete && complete(res);
        },
      });
    };
    // 判断是否需要验证登录
    // check_login ? App.doLogin(request) : request();
    request()
  },
  /**
   * post提交
   */
  _post_form(url, data, success, fail, complete) {
    wx.showNavigationBarLoading();
    let App = this;
    data.userid = wx.getStorageSync('user_id');
    let accessToken= wx.getStorageSync('sign');
    data.encoding = 'utf-8';
    wx.request({
      url: App.api_root + url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        accessToken: accessToken
      },
      method: 'POST',
      data: data,
      success(res) {
        if (res.statusCode !== 200 || typeof res.data !== 'object') {
          App.showError('网络请求出错');
          return false;
        }
        if (res.data.returnvalue == 1000) {
          // 授权
          return false;
        } else if (res.data.returnvalue == 'falseNologin') {
          // 登录态失效, 重新登录
          wx.hideNavigationBarLoading();
          App.showError('登录过期,请重新登录', function () {
            App.doLogin();
          });

        } else if (res.data.returnvalue == -1) {
          App.showError(res.data.msg, function () {
            fail && fail(res);
          });
          return false;
        }
        success && success(res.data);
      },
      fail(res) {
        App.showError(res.errMsg, function () {
          fail && fail(res);
        });
      },
      complete(res) {
        wx.hideNavigationBarLoading();
        complete && complete(res);
      }
    });
  },
  /**
   * 验证是否存在user_info
   */
  validateUserInfo() {
    let user_id = wx.getStorageSync('user_id')?true:false;
    let sign = wx.getStorageSync('sign')?true:false;
    return  user_id && sign
  },
  /**
   * 对象转URL
   */
  urlEncode(data) {
    var _result = [];
    for (var key in data) {
      var value = data[key];
      if (value.constructor == Array) {
        value.forEach(function (_value) {
          _result.push(key + "=" + _value);
        });
      } else {
        _result.push(key + '=' + value);
      }
    }
    return _result.join('&');
  },
  /**
   * 设置当前页面标题
   */
  setTitle() {
    let App = this,
      wxapp;
    if (wxapp = wx.getStorageSync('wxapp')) {
      wx.setNavigationBarTitle({
        title: wxapp.navbar.wxapp_title
      });
    } else {
      App.getWxappBase(function () {
        App.setTitle();
      });
    }
  },
  /**
   * 设置navbar标题、颜色
   */
  setNavigationBar() {
    // 获取小程序基础信息
    this.getWxappBase(function (wxapp) {
      // 设置navbar标题、颜色
      wx.setNavigationBarColor({
        frontColor: wxapp.navbar.top_text_color.text,
        backgroundColor: wxapp.navbar.top_background_color
      })
    });
  },
  /**
   * 获取tabBar页面路径列表
   */
  getTabBarLinks() {
    return tabBarLinks;
  },
  /**
   * 缓存方法
    */
  getCache: function (key) {
    var value = undefined;
    try {
      value = wx.getStorageSync(key)
    } catch (e) {
    }
    return value;
  },
  setCache: function (key, value) {
    wx.setStorage({
      key: key,
      data: value
    })
  }
});